package generatorRepository

import (
	"CommonsProject/models"
	"CommonsProject/models/generatorModel"
	"CommonsProject/pkg/tools/sqlTool"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"log"
	"strings"
)

type TableProduceRepository struct {
	DB *gorm.DB
}

// AddSysTable 添加生成表
func (u TableProduceRepository) AddSysTable(table *generatorModel.Table) {
	table.ToLower()
	for i := range table.Columns {
		table.Columns[i].ToLower()
	}
	log.Println(table)
	if models.Database.Create(&table).Error != nil {
		panic(errors.New("添加表失败！"))
	}
}

// RemoveSysTable 删除生成表
func (u TableProduceRepository) RemoveSysTable(tableId int) {
	if err := models.Database.Delete(&generatorModel.Table{}, tableId).Error; err != nil {
		panic(errors.New("删除生成表失败！" + err.Error()))
	}
	models.Database.Model(generatorModel.Table{}).Where("id = ?", tableId).Association("Columns").Unscoped().Clear()
}

// ModifySysTable 修改生成表
func (u TableProduceRepository) ModifySysTable(table *generatorModel.Table) {
	table.ToLower()
	for i := range table.Columns {
		table.Columns[i].ToLower()
	}
	log.Println(table)
	if models.Database.Model(&table).Association("Columns").Unscoped().Replace(table.Columns) != nil {
		panic(errors.New("修改生成表失败！"))
	}
	err := models.Database.Session(&gorm.Session{FullSaveAssociations: true}).Save(&table).Error
	if err != nil {
		panic(errors.New("修改生成表失败！"))
	}
}

// FindSysTableById 查找生成表通过ID
func (u TableProduceRepository) FindSysTableById(tableId uint) generatorModel.Table {
	var table generatorModel.Table
	models.Database.Preload("Columns").Take(&table, tableId)
	return table
}

// FindSysTable 查找生成表
func (u TableProduceRepository) FindSysTable(table *generatorModel.Table, pageNum, pageSize int) sqlTool.PageInfo {
	generatorSQL, args, err := sqlTool.GeneratorSQL(*table)

	if err != nil {
		panic(errors.New(err.Error()))
	}

	sqlLimit := generatorSQL + fmt.Sprintf(" limit %d offset %d", pageSize, pageSize*(pageNum-1))
	var list []generatorModel.Table
	models.Database.Raw(sqlLimit, args...).Scan(&list)

	//优化一下
	generatorSQL = strings.Replace(generatorSQL, " * ", " count(1) ", 1)
	var count int64
	models.Database.Raw(generatorSQL, args...).Count(&count)
	return sqlTool.ToPageStruct(list, pageNum, pageSize, count)
}
